<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync = "error"
      @load="onLoad"
    >
      <van-cell
        v-for="(article, index) in list"
        :key="index"
        :title="article.title"
      />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search'

export default {
  name: 'searchResult',
  // 接收父组件传过来的值
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1, // 默认显示1页
      perPage: 15, // 默认煤业显示15条数据
      error: false
    }
  },
  created () {},
  mounted () {},
  methods: {
    async onLoad () {
      try {
        // 1.获取请求数据
        const { data } = await getSearchResult({
          // 传参
          page: this.page, // 页码
          per_page: this.perPage, // 每页大小
          q: this.searchText
        })

        if (Math.random() > 0.5) {
          JSON.parse('dsnajndjsa')
        }

        // console.log(data)
        // 2.将数据添加到列表中
        // 解构赋值
        // ... 扩展运算符
        const { results } = data.data
        this.list.push(...results)
        console.log(this.list)

        // 3.设置加载状态结束,触发加载时才会重新加载
        this.loading = false

        // 4.判断数据是否加载完毕
        if (results.length) {
          this.page++ // 更新获取下一页数据的页码
        } else {
          this.finished = true // 没有数据了，将加载状态设置结束，不再 onLoad
        }
      } catch (err) {
        // 展示加载失败的提示状态
        this.error = true

        // 加载失败了关闭loading
        this.loading = false
        // this.$toast('数据获取失败，请稍后重试')
      }
    }
  }
}
</script>

<style scoped lang="less"></style>
